<template>
  <div class="page-container">
    <div class="card-container with-header">
      <div class="card-header">
        <div class="header-title">{{ isEdit ? '编辑位置类型' : '添加位置类型' }}</div>
      </div>
      
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="custom-form"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类型名称" />
        </el-form-item>
        
        <el-form-item label="类型图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称">
            <template #append>
              <el-popover
                placement="top"
                width="300"
                trigger="click"
              >
                <template #reference>
                  <el-button>
                    <el-icon>
                      <component :is="form.icon || 'Location'" />
                    </el-icon>
                    选择图标
                  </el-button>
                </template>
                <div class="icon-selector">
                  <div 
                    v-for="icon in iconList" 
                    :key="icon"
                    class="icon-item"
                    @click="selectIcon(icon)"
                  >
                    <el-icon>
                      <component :is="icon" />
                    </el-icon>
                    <span class="icon-name">{{ icon }}</span>
                  </div>
                </div>
              </el-popover>
            </template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <div class="form-btns">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Location, Shop, House, Food, Sunrise, Mug, Tickets, 
  Van, GoodsFilled, Museum, OfficeBuilding, Place,
  MapLocation, Position, TrendCharts, School, Promotion
} from '@element-plus/icons-vue'
import { getLocationType, addLocationType, updateLocationType } from '@/api/location'

const route = useRoute()
const router = useRouter()

// 图标列表
const iconList = [
  'Location', 'MapLocation', 'Position', 'Place',
  'Shop', 'House', 'Food', 'Sunrise', 'Mug', 
  'Tickets', 'Van', 'GoodsFilled', 'Museum', 
  'OfficeBuilding', 'TrendCharts', 'School', 'Promotion'
]

// 判断是编辑还是新增
const isEdit = computed(() => {
  return route.params.id !== undefined
})

// 表单ref
const formRef = ref(null)

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  icon: 'Location',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入类型名称', trigger: 'blur' },
    { min: 2, max: 20, message: '类型名称长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  icon: [
    { required: true, message: '请选择图标', trigger: 'change' }
  ]
}

// 选择图标
const selectIcon = (icon) => {
  form.icon = icon
}

// 获取类型详情
const getDetail = async (id) => {
  try {
    const res = await getLocationType(id)
    const data = res.data
    
    // 填充表单
    Object.keys(form).forEach(key => {
      if (data[key] !== undefined) {
        form[key] = data[key]
      }
    })
  } catch (error) {
    console.error('获取类型详情失败:', error)
    ElMessage.error('获取类型详情失败')
  }
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEdit.value) {
        await updateLocationType(form.id, form)
        ElMessage.success('更新成功')
      } else {
        await addLocationType(form)
        ElMessage.success('添加成功')
      }
      
      // 返回列表页
      router.push('/location/type')
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    }
  })
}

// 取消操作
const cancel = () => {
  router.back()
}

// 初始化
onMounted(() => {
  // 如果是编辑模式，获取详情数据
  if (isEdit.value) {
    getDetail(route.params.id)
  }
})
</script>

<style lang="scss" scoped>
.icon-selector {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
  
  .icon-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 8px;
    cursor: pointer;
    border-radius: 4px;
    
    &:hover {
      background-color: $--background-color-base;
    }
    
    .el-icon {
      font-size: 20px;
      margin-bottom: 5px;
    }
    
    .icon-name {
      font-size: 12px;
      word-break: break-word;
      text-align: center;
    }
  }
}
</style> 